package io.terminus.spzx.gateway.auth;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.terminus.spzx.consts.GatewayConstant;
import io.terminus.spzx.consts.UserInfoConstant;
import io.terminus.spzx.model.entity.user.UserInfo;
import io.terminus.spzx.model.vo.common.Result;
import io.terminus.spzx.model.vo.common.ResultCodeEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

/**
 * @author lichunlong lcl253137@alibaba-inc.com
 * @desc 全局性的权限过滤器
 * @date 2024-11-18
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final RedisTemplate<String, String> redisTemplate;

    private final AntPathMatcher antPathMatcher;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        UserInfo userInfo = this.getUserInfo(request);

        String path = request.getURI().getPath();
        log.info("当前请求路径: {}", path);
        // 校验用户必须登录
        if (antPathMatcher.match(GatewayConstant.GATEWAY_LOGIN_AUTH_PATTERN, path) && Objects.isNull(userInfo)) {
            return out(exchange.getResponse());
        }

        return chain.filter(exchange);
    }

    /**
     * 获取当前登录用户的信息
     *
     * @param request HTTP请求
     * @return 用户信息
     */
    private UserInfo getUserInfo(ServerHttpRequest request) {
        UserInfo userInfo = null;
        String token = StringUtils.EMPTY;

        List<String> tokenList = request.getHeaders().get(UserInfoConstant.USERINFO_TOKEN_REQUEST_HEADER);
        if (CollectionUtils.isNotEmpty(tokenList)) {
            token = tokenList.get(0);
        }
        if (StringUtils.isNotEmpty(token)) {
            String cacheUserInfo = redisTemplate.opsForValue().get(UserInfoConstant.REDIS_USERINFO_TOKEN_KEY_PREFIX + token);
            if (StringUtils.isNotEmpty(cacheUserInfo)) {
                userInfo = JSON.parseObject(cacheUserInfo, UserInfo.class);
            }
        }
        return userInfo;
    }

    private Mono<Void> out(ServerHttpResponse response) {
        Result<Void> result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        byte[] bits = JSONObject.toJSONString(result).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        // 指定编码，否则在浏览器中会中文乱码
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        return response.writeWith(Mono.just(buffer));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
